package com.changou.system.FIlter;

import com.changou.system.Util.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

//这个是鉴权过滤器 ,验证token的
@Component
public class AuthorizeFilter implements Ordered, GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求
        ServerHttpRequest request = exchange.getRequest();
        //则获取响应
        ServerHttpResponse response = exchange.getResponse();
        //3.如果是登陆请求则放行
        if (request.getURI().getPath().contains("/admin/login")){
           return chain.filter(exchange);
        }
        //获取请求头,因为除了第一次登陆,后续的请求,都会在请求行的位置携带一个令牌,我们可以根据判断这个令牌来确定请求是否具有权限
        //可是令牌是怎么放入到请求行中的>??????我们的代码里好像没有写啊!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        HttpHeaders headers = request.getHeaders();
        //获取令牌是否存在
        String token = headers.getFirst("token");
        if (StringUtils.isEmpty(token)){
            //如果不存在,则向客户端返回错误信息,这个方法??????????
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //这个方法干嘛用的????不能returnnull????
            return response.setComplete();
        }


        //如果令牌存在,则解析令牌
        try{
            JwtUtil.parseJWT(token);
        }catch (Exception e){
            e.printStackTrace();
            //令牌解析失败
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //如果令牌合法,则放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
